package org.ucas.kgraph.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.ucas.kgraph.dto.CarryDto;
import org.ucas.kgraph.dto.RelationDto;
import org.ucas.kgraph.dto.ResponseDto;
import org.ucas.kgraph.entity.Relation;
import org.ucas.kgraph.entity.RelationType;
import org.ucas.kgraph.service.RelationService;
import org.ucas.kgraph.utils.exception.NotFoundException;

@RestController
public class RelationController {

  @Autowired
  private RelationService relationService;

  @RequestMapping(value = "/relations",method = RequestMethod.POST)
  public CarryDto<RelationDto> create(@RequestBody RelationDto relation){
	
    Relation tmp = new Relation();
    relation.writeTo(tmp);
    tmp = relationService.create(tmp);
    return CarryDto.of(RelationDto.of(tmp));
  }
  
  @RequestMapping(value = "/relations/rename",method = RequestMethod.PUT)
  public CarryDto<RelationDto> rename(@RequestBody RelationDto relation){
	Relation tmp = new Relation();
    relation.writeTo(tmp);
   
    tmp = relationService.rename(tmp);
    
    
    return CarryDto.of(RelationDto.of(tmp));
  }
  
  @RequestMapping(value = "/relations",method = RequestMethod.DELETE)
  public ResponseDto delete(@RequestBody RelationDto relation){
	
	Relation tmp = new Relation();
	relation.writeTo(tmp);
	
   // tmp.setCategory(RelationType.valueOf(category));
    relationService.delete(tmp);
    return ResponseDto.OK;
  }

  @RequestMapping(value = "/relations/{id:\\d+}",method = RequestMethod.DELETE)
  public ResponseDto delete(@PathVariable Long id){
    relationService.delete(id);
    return ResponseDto.OK;
  }

  @RequestMapping(value = "/relations/{id:\\d+}",method = RequestMethod.PUT)
  public CarryDto<RelationDto> update(@RequestBody RelationDto dto, @PathVariable Long id){
    Relation relation = relationService.load(id);
    if(relation==null) throw NotFoundException.Relation_NotExists;
    dto.writeTo(relation);
    relationService.save(relation);
    return CarryDto.of(RelationDto.of(relation));
  }

  @RequestMapping(value = "/relations/{id:\\d+}",method = RequestMethod.GET)
  public CarryDto<RelationDto> load(@PathVariable Long id){
    Relation relation = relationService.load(id);
    return CarryDto.of(RelationDto.of(relation));
  }

  @RequestMapping(value = "/relations/reparent", method = RequestMethod.POST)
  public CarryDto<RelationDto> reparent(
          @RequestParam("termId") Long termId,
          @RequestParam("oldParent") Long oldParent,
          @RequestParam("newParent") Long newParent
  ){
    Relation relation = relationService.reparent(termId,oldParent,newParent);
    return CarryDto.of(RelationDto.of(relation));
  }
}
